<?php

namespace App\Http\Controllers;

use App\Models\Cdr;
use App\Models\Contract;
use App\Models\Customer;
use App\Models\CustomerRemark;
use App\Models\Department;
use App\Models\Node;
use App\Models\Order;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;

class IndexController extends Controller
{

    public function index(Request $request)
    {

        $user = $request->user();
        $sip = $user->sip;
        if ($sip !== null){
            $data = [
                'sip_id' => $sip->id,
                'username' => $sip->username,
                'password' => $sip->password,
                'host' => config('freeswitch.host'),
                'uri' => $sip->username . '@' . config('freeswitch.host'),
                'wss_url' => config('freeswitch.wss_url'),
                'websocket_url' => config('freeswitch.websocket_url'),
            ];
        }else{
            $data = [
                'sip_id' => 0,
                'username' => null,
                'password' => null,
                'host' => config('freeswitch.host'),
                'uri' => null,
                'wss_url' => config('freeswitch.wss_url'),
                'websocket_url' => config('freeswitch.websocket_url'),
            ];
        }
        return View::make("layout", compact('data'));
    }

    public function console(Request $request)
    {
        $user = $request->user();
        //商机数量
        $customerCount = Customer::query()->where(function ($q) use ($user){
            if ($user->hasPermissionTo('bi.serviceConfig.customer_list_all')){
                return $q->where('owner_user_id','>=',0);
            }elseif ($user->hasPermissionTo('bi.serviceConfig.customer_list_department')){
                return $q->where('owner_department_id',$user->department_id);
            }else{
                return $q->where('owner_user_id',$user->id);
            }
        })->count();
        //待跟进数量（15天未跟进）
        $customerRemarkCount = Customer::query()
            ->where('owner_user_id',$user->id)
            ->where('is_end',0)
            ->where('status',3)
            ->where('follow_time','<',date('Y-m-d H:i:d',time() - 15*24*3600))
            ->count();
        //合同数量
        $contractCount = Contract::query()->where(function ($q) use ($user){
            if ($user->hasPermissionTo('bi.serviceConfig.contract_list_all')){
                return $q->where('owner_user_id','>=',0);
            }elseif ($user->hasPermissionTo('bi.serviceConfig.contract_list_department')){
                return $q->where('owner_department_id',$user->department_id);
            }else{
                return $q->where('owner_user_id',$user->id);
            }
        })->count();
        //订单数
        $orderCount = Order::query()->where(function ($q) use ($user){
            if ($user->hasPermissionTo('bi.serviceConfig.order_list_all')){
                return $q->where('owner_user_id','>=',0);
            }elseif ($user->hasPermissionTo('bi.serviceConfig.order_list_department')){
                return $q->where('owner_department_id',$user->department_id);
            }else{
                return $q->where('owner_user_id',$user->id);
            }
        })->count();
        return View::make("index.console",compact('customerCount','customerRemarkCount','contractCount','orderCount'));
    }

    public function cdrCount()
    {
        $data = [
            'months' => [],
            'calls' => [],
            'success' => [],
        ];
        for ($m=1;$m<=12;$m++){
            $data['year_month'][$m] = [
                'start' => mktime(0,0,0,$m,1,date('Y')),
                'end' => mktime(0,0,0,$m+1,1,date('Y')),
            ];
            $data['months'][] = $m.'月';
            $data['calls'][$m] = 0;
            $data['success'][$m] = 0;
        }
        Cdr::whereYear('created_at', date('Y'))
            ->orderBy('id')
            ->chunk(1000, function ($result) use(&$data){
                foreach ($result as $item) {
                    foreach ($data['year_month'] as $key=>$time){
                        if (strtotime($item->created_at)>=$time['start'] && strtotime($item->created_at)<$time['end']){
                            $data['calls'][$key] += 1;
                            if ($item->billsec>0){
                                $data['success'][$key] += 1;
                            }
                        }
                    }
                }
            });
        return $this->success('ok',$data);
    }

    public function customerCount()
    {
        $data = [];
        $nodes = Node::with('customer')->whereIn('type',[1,2])->orderBy('sort','asc')->get();
        foreach ($nodes as $node){
            $data[$node->name] = $node->customer->count();
        }
        return $this->success('ok',$data);
    }

    public function customer(Request $request)
    {
        if ($request->ajax()){
            $user = $request->user();
            $res = Customer::query()
                ->where('owner_user_id',$user->id)
                ->where('is_end',0)
                ->where('status',3)
                ->where('follow_time','<',date('Y-m-d H:i:d',time() - 15*24*3600))
                ->paginate($request->get('limit', 30));
            return $this->success('ok', $res->items(), $res->total());
        }
        return View::make('index.customer');
    }

    public function onlinecall()
    {
        return View::make('index.onlinecall');
    }

}
